<template>
  <div>
    <div style="display: flex; justify-content: flex-end">
      <el-form :model="queryParams" class="filter-form-inline" label-position="right" size="small">
        <el-row :gutter="40" style="margin-left: 0px; margin-right: 0px">
          <el-form-item label="产品信息" style="width:300px;margin-right:20px;">
            <el-select v-model="queryParams.productId" clearable placeholder="请选择产品" @change="handlChangeProduct">
              <el-option v-for="item in productList" :key="item.productId" :label="item.productName"
                         :value="item.productId"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <filter-popover :form-list="formList" right="20px" @onConfirm="filterDataConfirm" @onReset="filterReset"/>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <el-table :cell-style="cellStyle" :data="tableData" border header-cell-class-name="table-header" size="medium"
              @row-click="aloneClick">
      <el-table-column :min-width="160" :show-overflow-tooltip="true" fixed="left" header-align="center" label="终端名称"
                       prop="terminalName"/>

      <el-table-column :min-width="160" :show-overflow-tooltip="true" align="center" fixed="left" label="终端所在地区">
        <template #default="{row}">
          {{ row.provinceName }}/{{ row.cityName }}/{{ row.areaName }}
        </template>
      </el-table-column>

      <el-table-column :min-width="160" :show-overflow-tooltip="true" fixed="left" header-align="center" label="产品名称"
                       prop="productPopularName"/>

      <el-table-column :min-width="160" :show-overflow-tooltip="true" header-align="center" label="批准文号"
                       prop="approvalNumber"/>

      <el-table-column :min-width="140" :show-overflow-tooltip="true" align="center" label="包装规格" prop="packSpecs"/>

      <el-table-column :show-overflow-tooltip="true" align="center" label="终端价(元)" prop="terminalPrice" width="120">
        <template #default="{row}">
          <div style="text-align: right">
            {{ isInteger(row.terminalPrice) }}
          </div>
        </template>
      </el-table-column>

      <el-table-column :show-overflow-tooltip="true" align="center" label="交易价(元)" prop="tradePrice" width="140">
        <template #default="{row}">
          <div style="text-align: right">
            {{ isInteger(row.tradePrice) }}
          </div>
        </template>
      </el-table-column>

      <el-table-column :min-width="160" :show-overflow-tooltip="true" align="center" label="配送商">
        <template #default="{row}">
          <distributors-view v-if="row.distributeContractDetails && row.distributeContractDetails.length"
                             :datas="row.distributeContractDetails" :unit="row.productInfoDetail?.sellUnit"/>
        </template>
      </el-table-column>

      <el-table-column :show-overflow-tooltip="true" align="center" label="开发保证金(元)" prop="devEarnestMoney" width="140">
        <template #default="{row}">
          <div style="text-align: right">
            {{ isInteger(row.devEarnestMoney) }}
          </div>
        </template>
      </el-table-column>

      <el-table-column :show-overflow-tooltip="true" align="center" label="开发期限截止" width="120">
        <template #default="{row}">
          {{ dateFormat("yyyy-mm-dd", row.expireTime) }}
        </template>
      </el-table-column>

      <el-table-column :show-overflow-tooltip="true" align="center" fixed="right" label="注册日期" width="120">
        <template #default="{row}">
          {{ dateFormat("yyyy-mm-dd", row.agentRegisterTime) }}
        </template>
      </el-table-column>

      <el-table-column :show-overflow-tooltip="true" align="center" fixed="right" label="状态" prop="address" width="160">
        <template #default="{row}">
          <div v-if="row.flowStatus!=='DOING'" style="line-height: 20px">{{ getLabel('fine_terminal', row.devStatus) }}
          </div>
          <div v-if="row.flowStatus ==='DOING'" style="line-height: 20px">
            {{ getLabel('approval_result', row.flowStatus) }}
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.page"
                :total="total" style="display: flex; justify-content: flex-end" @pagination="handlList"/>

    <!--设置配送信息-->
    <setiDelivery ref="setiDeliveryDialog"/>
    <!-- 开发中终端详情 -->
    <detail-drawer ref="detailDrawer" :size-width="1000" custom-title>
      <template #title>
        <div style="display: flex;justify-content: space-between;align-items: center">
          <div style="width: 40%">
            <span style="padding-right: 15px">{{ productData?.terminalName }} </span>
            <el-tag v-if="productData.flowStatus!=='DOING'" :type="statusType" size="small">
              {{ getLabel('fine_terminal', productData.devStatus) }}
            </el-tag>
            <el-tag v-if="productData.flowStatus ==='DOING'" :type="statusType" size="small">
              {{ getLabel('approval_result', productData.flowStatus) }}
            </el-tag>
          </div>
        </div>

      </template>
      <template #contents>
        <div class="drawer-content">
          <div class="history-list">
            <product-detail ref="productDetailDrawer" :product-id="productData.id"/>
          </div>
        </div>
      </template>
    </detail-drawer>
  </div>
</template>

<script>
import {defineAsyncComponent, getCurrentInstance, inject, onMounted, reactive, toRefs,} from "vue";
import {useRoute, useRouter} from "vue-router";
import {crmStore} from "@CRM/store";

export default {
  name: "Development",
  components: {
    setiDelivery: defineAsyncComponent(() =>
        import("@CRM/views/marketing/customer/terminal/modules/setiDelivery.vue")
    ),
    productDetail: defineAsyncComponent(() =>
        import("@CRM/views/marketing/customer/terminal/modules/productDetail.vue")
    ),
  },
  setup(props, context) {
    const api = inject("api");
    const router = useRouter();
    const route = useRoute();
    const currentInstance = getCurrentInstance();
    var data = reactive({
      tableData: [],
      formTerminal: null,
      queryParams: {
        agentId: Number(route.query.id),
        pageSize: 20,
        page: 1,
        keyWord: "",
        productId: "",
        devStatus: "",
        registerStartTime: null, // 必须
        registerEndTime: null, //
        expireTimeStart: null,
        expireTimeEnd: null,
        provinceCode: "",
        cityCode: "",
        areaCode: "",
      },
      total: 0,
      detailDrawer: null,
      setiDeliveryDialog: null,
      productDetailDrawer: null,
      productData: null,
      productList: [],
      devStatusList: crmStore.getters["dictionary/getDictionary"][
          "devStatus"
          ].filter((a) => a.value !== "5"),
      formList: [
        {
          key: 'devStatus',
          label: '状态',
          form_type: 'select',
          value: '',
          is_search: false,
          options: crmStore.getters['dictionary/getDictionary']['devStatus'].filter(a => a.value !== '5'),
        },
        {
          key: 'agentType',
          label: '营销模式',
          form_type: 'select',
          value: '',
          is_search: false,
          options: crmStore.getters['dictionary/getDictionary']['agentType'],
        },
        {
          key: 'agentName',
          label: '渠道客户名称',
          form_type: 'text',
          value: '',
          is_search: false,
          options: [],
        },
        {
          key: 'distributeName',
          label: '配送商名称',
          form_type: 'text',
          value: '',
          is_search: false,
          options: [],
        },
        {
          key: 'date_range1',
          label: '注册日期',
          form_type: 'daterange',
          value: [],
          is_search: false,
          options: [],
        },
        {
          key: 'date_range2',
          label: '开发截止日期',
          form_type: 'daterange',
          value: [],
          is_search: false,
          options: [],
        },
      ]
    });

    const handlAdd = () => {
      data.formTerminal.open();
    };

    // 确定搜所
    const filterDataConfirm = (val) => {
      data.queryParams.productId = val.productId;
      data.queryParams.keyWord = val.keyWord;
      data.queryParams.registerStartTime = val.date_range1[0];
      data.queryParams.registerStartTime = val.date_range1[1];
      data.queryParams.expireTimeStart = val.date_range2[0];
      data.queryParams.expireTimeEnd = val.date_range2[1];
      data.queryParams.provinceCode = val.area[0];
      data.queryParams.cityCode = val.area[1];
      data.queryParams.areaCode = val.area[2];
      data.queryParams.page = 1;
      handlList();
    };

    // 取消
    const filterReset = () => {
      data.queryParams = {
        agentId: Number(route.query.id),
        pageSize: 20,
        page: 1,
        keyWord: "",
        productId: "",
        devStatus: "",
        registerStartTime: null, // 必须
        registerEndTime: null, //
        expireTimeStart: null,
        expireTimeEnd: null,
        provinceCode: "",
        cityCode: "",
        areaCode: "",
      };
      handlList();
    };

    // 获取产品下拉
    const handlProductData = async () => {
      const a = {
        id: Number(route.query.id),
        type: 1,
        productPopularName: "",
      };
      const res = await api.terminal.TERMINAL_PRODUCTIDSS(a);
      if (res.code === 0) {
        data.productList = res.data.agentProduct;
        data.formList[0].options = res.data.agentProduct;
      }
    };

    // 产品事件
    const handlChangeProduct = (val) => {
      if (val) {
        data.queryParams.productId = val;
      } else {
        data.queryParams.productId = 0;
      }
      data.queryParams.page = 1;
      handlList();
    };

    // 获取列表
    const handlList = () => {
      const a = JSON.parse(JSON.stringify(data.queryParams));
      a.productId = Number(a.productId);
      api.channelAgent.PARTTIMEBIGBAG_TERMINAL_CREATE(a).then((res) => {
        if (res.code === 0) {
          data.tableData = res.data.list || [];
          data.total = res.data.total;
        }
      });
    };

    // 设置配送信息
    const handlSet = (val) => {
      data.setiDeliveryDialog.open(val);
    };

    const aloneClick = (row, column, event) => {
      if (column.label === "操作" || column.label === "查看文件") return;
      data.detailDrawer.open();
      data.productData = row;
      data.productId = row.id;
    };

    const cellStyle = () => {
      return "cursor:pointer;";
    };

    const handlFailure = (row, num) => {
      currentInstance.proxy
          .alertBox({
            message: "确认更改该终端产品状态为开发失败？",
          })
          .then(() => {
            api.terminal.TERMINAL_FAILURE(row.id).then((res) => {
              if (res.code) {
                currentInstance.proxy.customMessage({
                  type: "error",
                  message: res.msg,
                });
              } else {
                if (num === 2) {
                  data.productDetailDrawer.handlDetail();
                } else {
                  handlList();
                }
              }
            });
          })
          .catch((err) => {
            console.log(err);
          });
    };

    // 删除
    const handlDele = (id, num) => {
      currentInstance.proxy
          .alertBox({
            message: "删除数据后不可恢复,确定删除？",
          })
          .then(() => {
            api.terminal.REGISTERED_DELETE(id).then((res) => {
              if (res.code === 0) {
                if (num === 2) {
                  data.detailDrawer.close();
                } else {
                  handlList();
                }
              } else {
                currentInstance.proxy.customMessage({
                  type: "error",
                  message: res.msg,
                });
              }
            });
          })
          .catch((err) => {
            console.log(err);
          });
    };

    onMounted((_) => {
      handlList();
      handlProductData();
    });
    return {
      ...toRefs(data),
      handlAdd,
      aloneClick,
      cellStyle,
      handlList,
      handlSet,
      handlFailure,
      handlDele,
      handlChangeProduct,
      handlProductData,
      filterReset,
      filterDataConfirm,
    };
  },
};
</script>

<style scoped>
/* @import url(); 引入css类 */
</style>
